<template>
  <BaseDialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="dialogTitle"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <BaseForm
      ref="formRef"
      v-model="form"
      :rules="rules"
      :disabled="mode === 'view'"
      :loading="submitLoading"
      :validate-on-submit="true"
      @submit="handleSubmit"
      @reset="handleClose"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="字段中文名" prop="fieldNameCn">
            <el-input
              v-model="form.fieldNameCn"
              placeholder="请输入字段中文名"
              @blur="handleTranslateFieldName"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字段英文名" prop="fieldNameEn">
            <el-input
              v-model="form.fieldNameEn"
              placeholder="请输入字段英文名"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="字段类型" prop="fieldType">
            <el-select
              v-model="form.fieldType"
              placeholder="选择字段类型"
              style="width: 100%"
            >
              <el-option
                v-for="type in columnTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="默认值" prop="defaultValue">
            <el-input
              v-model="form.defaultValue"
              placeholder="请输入默认值"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="字段长度" prop="fieldLength">
            <el-input-number
              v-model="form.fieldLength"
              :min="1"
              :max="9999"
              placeholder="请输入字段长度"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小数位数" prop="fieldScale">
            <el-input-number
              v-model="form.fieldScale"
              :min="0"
              :max="10"
              placeholder="请输入小数位数"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="字段注释" prop="fieldComment">
        <el-input
          v-model="form.fieldComment"
          type="textarea"
          :rows="2"
          placeholder="请输入字段注释"
        />
      </el-form-item>

      <el-form-item label="字段约束">
        <el-checkbox-group v-model="form.constraints">
          <el-checkbox label="isRequired">必填</el-checkbox>
          <el-checkbox label="isPrimaryKey">主键</el-checkbox>
          <el-checkbox label="isUnique">唯一</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="状态" prop="isEnabled">
        <el-switch
          v-model="form.isEnabled"
          :disabled="mode === 'view'"
        />
      </el-form-item>

      <template #actions v-if="mode !== 'view'">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>

      <template #actions v-else>
        <el-button @click="handleClose">关闭</el-button>
      </template>
    </BaseForm>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, reactive } from 'vue'
import BaseDialog from '@/components/common/dialogs/BaseDialog.vue'
import BaseForm from '@/components/common/forms/BaseForm.vue'
import type {
  CreateFieldLibraryRequest,
  UpdateFieldLibraryRequest,
  FieldLibrary
} from '@/types/business/fieldLibrary'
import fieldLibraryService from '@/services/fieldLibraryService'
import { ColumnType } from '@/types/business/fieldLibrary'

const props = defineProps<{
  modelValue: boolean
  fieldData: FieldLibrary | null
  productId?: number
  mode: 'add' | 'edit' | 'view'
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()


// 响应式数据
const formRef = ref()
const submitLoading = ref(false)

// 表单数据
const form = reactive<CreateFieldLibraryRequest & { constraints: string[] }>({
  productId: props.productId || 0,
  fieldNameCn: '',
  fieldNameEn: '',
  fieldType: ColumnType.VARCHAR,
  fieldLength: undefined,
  fieldScale: undefined,
  isRequired: false,
  isPrimaryKey: false,
  isUnique: false,
  defaultValue: '',
  fieldComment: '',
  isEnabled: true,
  constraints: []
})

// 字段类型选项
const columnTypeOptions = [
  { label: 'VARCHAR', value: ColumnType.VARCHAR },
  { label: 'CHAR', value: ColumnType.CHAR },
  { label: 'TEXT', value: ColumnType.TEXT },
  { label: 'INT', value: ColumnType.INT },
  { label: 'INTEGER', value: ColumnType.INTEGER },
  { label: 'BIGINT', value: ColumnType.BIGINT },
  { label: 'DECIMAL', value: ColumnType.DECIMAL },
  { label: 'NUMERIC', value: ColumnType.NUMERIC },
  { label: 'DATE', value: ColumnType.DATE },
  { label: 'DATETIME', value: ColumnType.DATETIME },
  { label: 'TIMESTAMP', value: ColumnType.TIMESTAMP },
  { label: 'BOOLEAN', value: ColumnType.BOOLEAN }
]

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    add: '新增字段',
    edit: '编辑字段',
    view: '查看字段详情'
  }
  return titles[props.mode]
})

// 验证规则
const rules = {
  fieldNameCn: [
    { required: true, message: '请输入字段中文名', trigger: 'blur' }
  ],
  fieldType: [
    { required: true, message: '请选择字段类型', trigger: 'change' }
  ]
}

// 监听对话框显示
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 初始化表单
const initForm = () => {
  if (props.mode === 'edit' && props.fieldData) {
    Object.assign(form, {
      productId: props.productId,
      fieldNameCn: props.fieldData.fieldNameCn,
      fieldNameEn: props.fieldData.fieldNameEn,
      fieldType: props.fieldData.fieldType,
      fieldLength: props.fieldData.fieldLength,
      fieldScale: props.fieldData.fieldScale,
      isRequired: props.fieldData.isRequired,
      isPrimaryKey: props.fieldData.isPrimaryKey,
      isUnique: props.fieldData.isUnique,
      defaultValue: props.fieldData.defaultValue,
      fieldComment: props.fieldData.fieldComment,
      isEnabled: props.fieldData.isEnabled,
      constraints: []
    })

    // 设置约束复选框
    form.constraints = []
    if (form.isRequired) form.constraints.push('isRequired')
    if (form.isPrimaryKey) form.constraints.push('isPrimaryKey')
    if (form.isUnique) form.constraints.push('isUnique')
  } else if (props.mode === 'add') {
    Object.assign(form, {
      productId: props.productId,
      fieldNameCn: '',
      fieldNameEn: '',
      fieldType: ColumnType.VARCHAR,
      fieldLength: undefined,
      fieldScale: undefined,
      isRequired: false,
      isPrimaryKey: false,
      isUnique: false,
      defaultValue: '',
      fieldComment: '',
      isEnabled: true,
      constraints: []
    })
  }
}

// 翻译字段名称
const handleTranslateFieldName = async () => {
  if (!form.fieldNameCn) return

  try {
    const response = await fieldLibraryService.translateFieldName(form.fieldNameCn)
    if (response.success && response.data && response.data.length > 0) {
      // 可以在此处显示翻译建议对话框
      form.fieldNameEn = response.data[0]
    }
  } catch (error) {
    console.error('翻译失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 更新约束状态
    form.isRequired = form.constraints.includes('isRequired')
    form.isPrimaryKey = form.constraints.includes('isPrimaryKey')
    form.isUnique = form.constraints.includes('isUnique')

    submitLoading.value = true

    if (props.mode === 'add') {
      // 创建新对象，排除 constraints 字段
      const { constraints, ...createData } = form
      await fieldLibraryService.createField(createData as CreateFieldLibraryRequest)
    } else if (props.mode === 'edit' && props.fieldData) {
      const { constraints, ...updateData } = form
      const updateRequest = { ...updateData, productId: undefined } as UpdateFieldLibraryRequest
      delete (updateRequest as any).productId
      await fieldLibraryService.updateField(props.fieldData.id, updateRequest)
    }

    emit('success')
  } catch (error: any) {
    console.error('提交失败:', error)
    throw error // 让BaseForm处理错误消息
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}
</script>
